<template>
  <el-dialog v-el-drag-dialog title="规格参数" :visible.sync="visible" :append-to-body="appendToBody" :before-close="onClose">
    <el-card style="margin:0 0 5px 5px">
      <el-tabs tab-position="left">
        <el-tab-pane
          v-for="(group, g_index) in attrData.attrGroups"
          :key="group.attrGroupId"
          :label="group.attrGroupName"
        >
          <el-row :gutter="20">
            <el-col :span="20">
              <el-form ref="baseAttrForm" :model="attrData" label-width="120px">
                <el-form-item
                  v-for="(attr, a_index) in group.attrs"
                  :key="attr.attrId"
                  :label="attr.attrName"
                >
                  <el-input v-model="attrData.baseAttrs[g_index][a_index].attrId" type="hidden" v-show="false" />
                  <el-select
                    v-model="attrData.baseAttrs[g_index][a_index].attrValue"
                    :multiple="attr.valueType === '1'"
                    filterable
                    allow-create
                    default-first-option
                    placeholder="请选择或输入值"
                    class="m-l-10 w-75"
                  >
                    <el-option
                      v-for="(val, v_index) in attr.valueSelect.split(';')"
                      :key="v_index"
                      :label="val"
                      :value="val"
                    />
                  </el-select>
                  <el-checkbox
                    v-model="attrData.baseAttrs[g_index][a_index].showDesc"
                    true-label="0"
                    false-label="1"
                    class="m-l-10"
                  >
                    是否使用
                  </el-checkbox>
                </el-form-item>
              </el-form>
            </el-col>
            <el-col :span="4">
              <el-button @click="handleBaseAttr(group.attrGroupId)" type="primary" size="mini" circle icon="el-icon-plus" />
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <attr-form-dialog v-if="openAttrFormDialog" ref="attrForm" @confirmForm="refreshBaseAttrs" />

    <span slot="footer" class="dialog-footer">
      <el-button v-if="hasLoaded" type="primary" icon="el-icon-check" @click="onSubmit">确 定</el-button>
      <el-button icon="el-icon-close" @click="onClose">关 闭</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { groupAttrInfo, attrValueList } from '@/api/mall/product/attrgroup'
import { updateAttrValue } from '@/api/mall/product/spu'
import AttrFormDialog from '@/views/mall/product/attr/base/form/dialog'

export default {
  name: 'BaseAttrDialog',
  components: {
    AttrFormDialog
  },
  data() {
    return {
      visible: false,
      appendToBody: false,
      hasLoaded: false,
      spuId: '',
      catalogId: '',
      attrData: {
        attrGroups: [],
        baseAttrs: []
      },
      attrMap: {},
      openAttrFormDialog: false
    }
  },
  methods: {
    init(spuId, catalogId) {
      this.hasLoaded = false
      this.spuId = spuId
      this.catalogId = catalogId
      this.visible = true
      this.$nextTick(() => {
        this.getSpuAttrs()
        this.getBaseAttrs()
        this.hasLoaded = this.$perm.hasPermissionOr(['mall:product:spu'])
      })
    },
    getSpuAttrs() {
      attrValueList({
        Q_spuId_L_EQ: this.spuId
      }).then(response => {
        response.forEach(info => {
          this.attrMap[info.attrId + ''] = info
        })
      }).catch(e => {})
    },
    getBaseAttrs() {
      groupAttrInfo(this.catalogId, { attrType: 1 }).then(response => {
        let _this = this
        response.forEach(item => {
          let attrs = []
          item.attrs.forEach(info => {
            let val = ''
            if (_this.attrMap[info.attrId + '']) {
              val = _this.attrMap[info.attrId + ''].attrValue.split(';')
              if (val.length === 1) {
                val = val[0] + ''
              }
            }
            attrs.push({
              attrId: info.attrId,
              attrName: info.attrName,
              attrValue: val,
              showDesc: _this.attrMap[info.attrId + '']
                  ? _this.attrMap[info.attrId + ''].quickShow
                  : info.showDesc
            })
          })
          this.attrData.baseAttrs.push(attrs)
        })
        this.attrData.attrGroups = response
      }).catch(e => {})
    },
    handleBaseAttr(groupId) {
      this.openAttrFormDialog = true
      this.$nextTick(() => {
        this.$refs.attrForm.init(undefined, this.catalogId, '1', groupId)
      })
    },
    refreshBaseAttrs() {
      let tempAttrs = []
      tempAttrs.push(this.attrData.baseAttrs)
      groupAttrInfo(this.catalogId, { attrType: '1' }).then(response => {
        let attrs = []
        response.forEach(item => {
          item.attrs.forEach(info => {
            let index = tempAttrs.findIndex((item_) => item_.attrId === info.attrId)
            if (index === -1) {
              attrs.push({
                attrId: info.attrId,
                attrValue: '',
                showDesc: info.showDesc
              })
            }
          })
        })

        this.attrData.baseAttrs.push(attrs)
      }).catch(e => {})
    },
    onSubmit() {
      let submitData = []
      this.attrData.baseAttrs.forEach(attrs => {
        attrs.forEach(attr => {
          let val = ''
          if (attr.attrValue instanceof Array) {
            val = attr.attrValue.join(';')
          } else {
            val = attr.attrValue
          }

          if (val !== '') {
            submitData.push({
              attrId: attr.attrId,
              attrName: attr.attrName,
              attrValue: val,
              showDesc: attr.showDesc
            })
          }
        })
      })

      updateAttrValue(this.spuId, submitData).then(response => {
        this.$modal.msgSuccess(response.msg)
        this.$emit('confirmForm')
        this.spuId = ''
        this.catalogId = ''
        this.attrData = {
          attrGroups: [],
          baseAttrs: []
        }
        this.attrMap = {}
        this.visible = false
      }).catch(() => {})
    },
    onClose() {
      this.spuId = ''
      this.catalogId = ''
      this.attrData = {
        attrGroups: [],
        baseAttrs: []
      }
      this.attrMap = {}
      this.visible = false
    }
  }
}
</script>
